package com.wmh.baseservice.merchant.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.config.KeyConfig;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import com.wmh.baseservice.common.mybatisplus.structure.CustomQueryWrapper;
import com.wmh.baseservice.common.redis.utils.RedisUtil;
import com.wmh.baseservice.common.shiro.config.ShiroConfig;
import com.wmh.baseservice.common.shiro.jwt.JwtTokenUtil;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.ShiroMd5Util;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.mapper.MerchantInfoMapper;
import com.wmh.baseservice.merchant.pojo.*;
import com.wmh.baseservice.merchant.service.MerchantIncomeExpendService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.merchant.service.MerchantMenuService;
import com.wmh.baseservice.merchant.service.MerchantRoleMenuService;
import com.wmh.baseservice.system.pojo.SysParams;
import com.wmh.baseservice.system.service.SysParamsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wmh generator
 * @since 2021-12-24
 */
@Service
public class MerchantInfoServiceImpl extends CommonServiceImpl<MerchantInfoMapper, MerchantInfo> implements MerchantInfoService {

    @Resource
    private MerchantInfoMapper merchantInfoMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private MerchantMenuService merchantMenuService;
    @Resource
    private MerchantRoleMenuService merchantRoleMenuService;
    @Resource
    private SysParamsService sysParamsService;
    @Resource
    private MerchantIncomeExpendService merchantIncomeExpendService;

    @Override
    public String authority(String account, String password) {
        // 获取管理员用户账号信息
        MerchantInfo merchantInfo = merchantInfoMapper.selectOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.ACCOUNT, account));
        if (null == merchantInfo) {
            return ReturnBody.error("用户名不存在");
        }
        if (!ShiroMd5Util.decodePwd(merchantInfo.getPassword(), password + KeyConfig.SHIRO_SALE, merchantInfo.getSalt())) {
            return ReturnBody.error("用户名或密码错误");
        }
        if (merchantInfo.getStatus() != 0) {
            return ReturnBody.error("该账号已被冻结, 请联系相关人员");
        }
        JSONObject jsonObject = new JSONObject();
        if (CommUtil.checkNull(merchantInfo.getStoreAvatar())) {
            jsonObject.put("storeAvatar", merchantInfo.getStoreAvatar());
        }
        // 秘钥
        String token = "Bearer_" + JwtTokenUtil.generateToken(merchantInfo.getUsId(), merchantInfo.getAccount() + ShiroConfig.SHIRO_MERCHANT + ":" + password, 6_000_000);
        jsonObject.put("token", token);
        // 角色菜单
        List<MerchantMenu> roleMenu = getRoleMenu(merchantInfo.getRoleId(), merchantInfo.getParentId(), merchantInfo.getType())
                .stream().sorted(Comparator.comparing(MerchantMenu::getSort)).collect(Collectors.toList());
        jsonObject.put("menuList", roleMenu);
        jsonObject.put("preList", roleMenu.stream().filter(item -> item.getFlag() == 2).map(MerchantMenu::getRequestUrl).collect(Collectors.toList()));
        return ReturnBody.success(jsonObject);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void marginPay(Long merchantId) {
        SysParams sysParams = sysParamsService.getByIdForUpdate(11L);
        BigDecimal money = new BigDecimal(sysParams.getValue());
        //商家加保证金
        MerchantInfo info = getByIdForUpdate(merchantId);
        info.setMargin(info.getMargin().add(money));
        if (!updateById(info)) {
            throw new ServiceException();
        }
        //添加商家支出流水
        MerchantIncomeExpend merchantIncomeExpend = new MerchantIncomeExpend().setStatus(-1).setRemark("缴纳保证金")
                .setMoney(money).setOrderNum("缴纳保证金").setMerchantId(info.getId());
        if (!merchantIncomeExpendService.save(merchantIncomeExpend)) {
            throw new ServiceException();
        }

    }

    @Override
    public MerchantVegetablePlot queryPlotStatus(Long id) {
        return merchantInfoMapper.queryPlotStatus(id);
    }

    // 获取该角色拥有权限的菜单
    private List<MerchantMenu> getRoleMenu(Long roleId, Long id, Integer type) {
        MerchantRoleMenu merchantRoleMenu = new MerchantRoleMenu();
        List<MerchantMenu> list;
        if (id != -1 || type == 2 || type == 3) {
            //父级id不为-1或者商家类型为租赁入驻或者为仅拼单商家，查询父级id给他分配的菜单
            merchantRoleMenu.setRoleId(roleId);
            list = merchantRoleMenuService.selectRoleMenu(merchantRoleMenu);
        } else {
            //-1为加盟申请人，拥有全部菜单
            QueryWrapper<MerchantMenu> queryWrapper = new CustomQueryWrapper<MerchantMenu>().orderByDesc(MerchantMenu.SORT);
            list = merchantMenuService.list(queryWrapper);
        }
        if (list.size() > 0) {
            //过滤商单管理
            list = list.stream().filter(item -> !item.getId().equals(108L) && !item.getParentId().equals(108L)).collect(Collectors.toList());
            redisUtil.hset("MerchantRoleMenu", roleId.toString(), list);
        } else {
            throw new ServiceException("获取菜单列表失败,可能是申请人还未给您的账号分配对应的菜单权限");
        }
        return list;
    }
}
